<?php
namespace app\index\controller;
use think\Controller;

class Oauth extends Controller
{
	private $client_id = 'shangang-wisdom-union-system';
	private $client_secret = 'shangang-wisdom-union-system';
	private $redirect_uri = 'http://117.39.28.234:8023/index/oauth/index';
	
	public function index()
	{
		$code = trim($_GET['code']);
		$state = trim($_GET['state']);
		
		$url = 'http://www.sxjbjt.com:9538/platform/api/operation-platform/platform-auth/oauth/token';
		$headers = array('Authorization'=>'basic '.base64_encode($this->client_id.':'.$this->client_secret), 'Content-Type'=>'application/x-www-form-urlencoded');
		$params = array('client_id'=>$this->client_id, 'grant_type'=>'authorization_code', 'code'=>$code, 'state'=>$state, 'redirect_uri'=>$this->redirect_uri);
		
		$result = $this->requestUrl($url, 'POST', $params, true, $headers);
		//var_dump($result);exit;
		echo json_encode(array('result'=>$result));
		exit;
	}	
	
	protected function requestUrl($url, $method = 'GET', $params = array(), $json_=true,$headers = array())
    {
		/* $curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params));
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_TIMEOUT, 300);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		
		$data  = curl_exec($curl);
		curl_close($curl);
		if ($json_) $data = json_decode($data, true);
        return $data; */
		
        /**初始化一个数组设置curl*/
        $opts = array(
            CURLOPT_TIMEOUT         => 300,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_HTTPHEADER      => $headers
        );
        /**建立对应的http请求（get or post）*/
        switch (strtoupper($method))
        {
            /**post请求*/
            case 'POST':
                /**设置你需要抓取的URL*/
                $opts[CURLOPT_URL]        = $url;
                $opts[CURLOPT_POST]       = 1;
                $opts[CURLOPT_POSTFIELDS] = json_encode($params);
                break;
            /**get请求*/
            case 'GET':
                $URL_ = $url.'?'.http_build_query($params);
                $opts[CURLOPT_URL]        = $URL_;
                break;
            default:
                return false;
        }

        /**初始化一个 cURL 对象*/
        $curl = curl_init();
        /**运行CURL*/
        curl_setopt_array($curl, $opts);
        $data  = curl_exec($curl);
        $error = curl_error($curl);
        /**关闭URL请求*/
        curl_close($curl);
        /**请求出错*/
        if($error) return false;

        /**转换json数组返回*/
        if ($json_) $data = json_decode($data, true);
        return $data;
    }
}
